package com.neusoft.controller;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.neusoft.config.SendMail;
import com.neusoft.entity.Role;
import com.neusoft.entity.SystemMenu;
import com.neusoft.entity.User;
import com.neusoft.entity.UserQuery;
import com.neusoft.entity.common.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

@Controller
@RequestMapping("user/consumer")
public class UserConsumerController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private SystemMenuConsumerController systemMenuConsumerController;

    private String url_prefix = "http://localhost:8001";

//      private String url_prefix = "http://provider";

    @PostMapping("save")
    @ResponseBody
    public void save(User bean) {
        System.out.println("修改或添加的对象为：" + bean);
        String url = url_prefix + "/user/save";
        restTemplate.put(url, bean);
    }

    //保存记录last_login_data
    @PostMapping("save1")
    @ResponseBody
    public void save1(HttpServletRequest request) {
        System.out.println("保存记录last_login_data------");
        String url = url_prefix + "/user/save1";
        HttpSession session = request.getSession();   //获取session
        Enumeration<String> attrs = session.getAttributeNames();    // 获取session中所有的键值
        // 遍历attrs中的键值
        while (attrs.hasMoreElements()) {
            String name = attrs.nextElement().toString();   // 获取session键值
            if ("bean".equals(name)) {
                User bean = (User) session.getAttribute(name);// 根据键值取session中的值
                User bean1 = (User) queryById(bean.getId());
                bean.setPassword(bean1.getPassword());
                bean.setLastLoginDate(new Date());
                restTemplate.put(url,bean);
//                request.getSession().removeAttribute("bean");   //移除session保存的bean
                System.out.println("修改last_login_data------------------");
            }
        }

    }


    @PostMapping("queryAll")
    @ResponseBody
    public Object queryAll(Integer page, Integer limit, UserQuery bean) {
        System.out.println("bean值为：" + bean);
        System.out.println("page值为：" + page);
        System.out.println("limit值为：" + limit);
        String url = url_prefix + "/user/queryAll/" + page + "/" + limit;
        return restTemplate.postForObject(url, bean, CommonResult.class);
    }

    @RequestMapping("queryById/{id}")
    @ResponseBody
    public Object queryById(@PathVariable Integer id) {
        String url = url_prefix + "/user/queryById/" + id;
        return restTemplate.getForObject(url, User.class);
    }

    @RequestMapping("queryByRoleName/{name}")
    @ResponseBody
    public Object queryByRoleName(@PathVariable String name) {
        String url = url_prefix + "/user/queryByRoleName/" + name;
        return restTemplate.getForObject(url, Role.class);
    }

    @PostMapping("deleteById")
    @ResponseBody
    public ResponseEntity<Boolean> deleteById(Integer[] ids) {
        for (int i = 0; i < ids.length; i++) {
            System.out.println("ids值为：" + ids[i]);
        }
        StringBuffer sb = new StringBuffer();
        System.out.println(Arrays.toString(ids));
        sb.append(Arrays.toString(ids));
        sb.deleteCharAt(sb.indexOf("["));
        sb.deleteCharAt(sb.lastIndexOf("]"));
        System.out.println(sb.toString());
        String url = url_prefix + "/user/deleteById/" + sb.toString();
        return restTemplate.postForEntity(url, sb.toString(), Boolean.class);
    }

    @PostMapping("deleteById1")
    @ResponseBody
    public ResponseEntity<Boolean> deleteById1(Integer id) {
        String url = url_prefix + "/user/deleteById1/" + id;
        return restTemplate.postForEntity(url, id, Boolean.class);
    }


//

    @PostMapping("doPost")
    @ResponseBody
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取用户的邮箱
        String email = request.getParameter("email");
        PrintWriter out = response.getWriter();
        //实例化一个发送邮件的对象
        SendMail mySendMail = new SendMail();

        MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        map.add("email",email);
        String url = url_prefix + "/user/doPost/";
        //根据邮箱找到该用户信息
        User bean = restTemplate.postForObject(url,map,User.class);
        if (bean != null) {
            //设置收件人和消息内容
            mySendMail.sendMail(email, "尊敬的" + bean.getAccount() + "客户！后台管理系统提醒，您的密码为：" + bean.getPassword());
            System.out.println("恭喜，找回密码成功！");
        } else {
            System.out.println("该邮箱尚未注册！请重新输入。");
        }

    }


    //----------------------------------------------------------------------------------------
    //去到登录页面
    @RequestMapping("toLogin")
    public String toLogin() {
        return "login";
    }

    //去到注册页面
    @RequestMapping("toReg")
    public String toReg(Model model) {
        model.addAttribute("bean", new User());
        System.out.println("跳转到---user_reg.html");
        return "user/user_reg";
    }

    //去到找回密码页面
    @RequestMapping("toFind")
    public String toFind() {
        System.out.println("跳转到---find_password.html");
        return "user/find_password";
    }


    //去到index主页面
    @RequestMapping("login")
    public String login(String account,String password, HttpServletRequest request, Model model,HttpSession session) {

        MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        map.add("account",account);
        map.add("password",password);
        String url = url_prefix + "/user/login";
        User bean = restTemplate.postForObject(url,map,User.class);
//                ( + "/user/login",map,User.class);
        if (bean != null) {
            System.out.println(systemMenuConsumerController.queryAll1());
            ObjectMapper mapper = new ObjectMapper();
            List<SystemMenu> systemMenus= mapper.convertValue(systemMenuConsumerController.queryAll1(), new TypeReference<List<SystemMenu>>() { });
            for(SystemMenu systemMenu:systemMenus){
                systemMenu.setStatus(0);
                systemMenuConsumerController.save(systemMenu);
            }
            System.out.println(bean.getRoles());
            Role role = (Role) queryByRoleName(bean.getRoles());
            System.out.println("role对象为："+role);
            String menusIds = role.getMenus();
            String[] menusIds1 = menusIds.split(",");
            for(int i=0;i<menusIds1.length;i++) {
                SystemMenu systemMenu = (SystemMenu) systemMenuConsumerController.queryById(Integer.parseInt(menusIds1[i]));
                systemMenu.setStatus(1);
                systemMenuConsumerController.save(systemMenu);
            }
            //用户信息放入session
            System.out.println("登录...成功..." + "用户名：" + account);
            request.getSession().setAttribute(" bean",bean);
            session.setAttribute("bean",bean);
            model.addAttribute("user", bean);
            model.addAttribute("msg", "登录成功！");

            return "index";
        } else {

            //登录失败
            model.addAttribute("msg", "账号密码错误");
            System.out.println("登录...失败...");

            return "login";
        }

    }


    //根据密码查询数据库中是否有该用户的信息,并更新密码
//    @PostMapping("changePassword")
//    @ResponseBody
//    public Object changePassword(String oldPassword,String password) {
//        System.out.println("根据密码查询数据库中是否有该用户的信息并更新密码------");
//        MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
//        map.add("oldPassword",oldPassword);
//        map.add("password",password);
//        String url = url_prefix + "/user/save2";
//        return restTemplate.postForObject(url,map,User.class);
//    }
    @PostMapping("changePassword")
    @ResponseBody
    public Object changePassword(@RequestParam("account") String account,
                                 @RequestParam("oldPassword") String oldPassword,
                                 @RequestParam("newPassword") String newPassword) {
        MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        map.add("account",account);
        map.add("oldPassword",oldPassword);
        map.add("newPassword",newPassword);
        String url = url_prefix + "/user/changePassword";
        return restTemplate.postForObject(url,map,User.class);
    }

    //去到用户管理页面
    @RequestMapping("toList")
    public String toList() {
        return "user/user_list";
    }

    //去到修改页面
    @RequestMapping("/{id}")
    public String toEdit(@PathVariable Integer id, Model model) {
        User bean = (User) queryById(id);
        model.addAttribute("bean", bean);
        return "user/user_add";
    }

    //去到添加页面
    @RequestMapping("/")
    public String toAdd(Model model) {
        model.addAttribute("bean", new User());
        return "user/user_add";
    }


    //去到修改密码页面
    @RequestMapping("toPassword")
    public String toPassword() {
        return "user/user_password";
    }

    //去到修改密码页面
    @RequestMapping("toBaseUser")
    public String toBaseUser(Model model,HttpServletRequest request) {
        System.out.println("保存记录last_login_data------");
        String url = url_prefix + "/user/save1";
        HttpSession session = request.getSession();   //获取session
        Enumeration<String> attrs = session.getAttributeNames();    // 获取session中所有的键值
        // 遍历attrs中的键值
        while (attrs.hasMoreElements()) {
            String name = attrs.nextElement().toString();   // 获取session键值
            if ("bean".equals(name)) {
                User bean = (User) session.getAttribute(name);      // 根据键值取session中的值
                bean.setLastLoginDate(new Date());
                model.addAttribute("bean",bean);
                return "user/user-setting";
            }
        }
        return "user/user-setting";
    }
}
